/*
 * Copyright 2011 Kim Lindhardt Madsen
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package dk.lindhardt.gwt.geie.client.edit;

import com.google.gwt.event.dom.client.*;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import dk.lindhardt.gwt.geie.shared.CellFormat;

/**
 * User: AnAmuser
 * Date: 18-08-11
 * <p/>
 * Pattern
 */
public class PatternStyleMenu extends Composite implements StyleMenu {

   private MenuStateChangeHandler stateChangeHandler;

   private PatternBox patternBox;

   public PatternStyleMenu(MenuStateChangeHandler stateChangeHandler, CellFormat cellFormat) {
      this.stateChangeHandler = stateChangeHandler;

      VerticalPanel panel = new VerticalPanel();
      initWidget(panel);

      HorizontalPanel patternPanel = new HorizontalPanel();
      patternPanel.addStyleName("geie-menu");
      patternPanel.addStyleName("geie-pattern-menu");
      patternBox = new PatternBox(cellFormat);
      patternPanel.add(patternBox);

      panel.add(patternPanel);
   }

   public void transferValues(CellFormat cellFormat) {
      patternBox.transferValues(cellFormat);
   }

   private class PatternBox extends TextBox implements StyleMenu {

      private PatternBox(CellFormat cellFormat) {
         addKeyDownHandler(
               new KeyDownHandler() {
                  public void onKeyDown(KeyDownEvent event) {
                     int code = event.getNativeKeyCode();
                     if (KeyCodes.KEY_ENTER == code) {
                        stateChangeHandler.onPatternChanged();
                     }
                  }
               });
         addStyleName("geie-pattern-box");
         String pattern = cellFormat.getPattern();
         setText(pattern != null ? pattern : "");
      }

      public void transferValues(CellFormat cellFormat) {
         String pattern = patternBox.getText();
         if (pattern.length() > 0) {
            cellFormat.setPattern(pattern);
         } else {
            cellFormat.setPattern(null);
         }
      }
   }
}
